using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Text;
using System.Security.Cryptography;
/// <summary>
/// Class for encode and decode
/// </summary>
public class CypherTextUtil
{
    static long codenum = 201108200639;
    static string codestr = "75E11954";

    public static string DefaultEncrypt(string plainText)
    {
        return Encrypt(plainText, codestr + codenum.ToString());
    }
    public static string DefaultDecrypt(string cypherText)
    {
        return Decrypt(cypherText, codestr + codenum.ToString());
    }
    public static string MD5Encrypt(string strSource)
    {
        byte[] srcBytes = null;
        byte[] encodedByte = null;

        try
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            srcBytes = ASCIIEncoding.Default.GetBytes(strSource);
            encodedByte = md5.ComputeHash(srcBytes);

        }
        catch (Exception ex)
        {

        }
        return BitConverter.ToString(encodedByte).Replace("-", "").ToLower();

    }
    public static string Encrypt(string toEncrypt, string key)
    {
        byte[] keyArr;
        byte[] toEncryptArr = UTF8Encoding.UTF8.GetBytes(toEncrypt);
        try
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            keyArr = md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
            md5.Clear();
            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

            tdes.Key = keyArr;
            tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.ISO10126;
            ICryptoTransform cTransform = tdes.CreateEncryptor();
            byte[] rsArr = cTransform.TransformFinalBlock(toEncryptArr, 0, toEncryptArr.Length);

            tdes.Clear();
            return Convert.ToBase64String(rsArr);
        }
        catch (Exception ex) { }
        return "";
    }
    public static string Decrypt(string cypherString, string key)
    {
        byte[] keyArr = null;
        byte[] encryptedArr = null;
        try
        {
            encryptedArr = Convert.FromBase64String(cypherString);
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

            keyArr = md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
            md5.Clear();

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

            tdes.Key = keyArr;
            tdes.Padding = PaddingMode.ISO10126;
            tdes.Mode = CipherMode.ECB;
            ICryptoTransform cTransform = tdes.CreateDecryptor();
            byte[] resultArr = cTransform.TransformFinalBlock(encryptedArr, 0, encryptedArr.Length);
            tdes.Clear();
            return UTF8Encoding.UTF8.GetString(resultArr);
        }
        catch (Exception ex)
        {
        }
        return "";
    }
}

